{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Keras  \n",
    "\n",
    "`keras`的核心是`model`，最简单的模型是顺序模型`Sequential`，另一种是`Functional`。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import keras\n",
    "from keras.models import Sequential\n",
    "\n",
    "model = Sequential()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "然后可以使用`model.add()`来堆叠模型，即增加层：  \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from keras.layers import Dense\n",
    "model.add(Dense(units=64, activation='relu', input_dim=100))\n",
    "\n",
    "# 或者是例如图片分类的写法\n",
    "model = Sequential([\n",
    "    keras.Input(shape=[28,28,1]),\n",
    "    # .... \n",
    "    Dense(10, activation='softmax')\n",
    "])\n",
    "\n",
    "model.summary()  # 打印网络信息用"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "然后可以使用`model.compile`来配置学习过程，主要包括损失函数、优化器等：\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "model.compile(\n",
    "    loss='categorical_crossentropy',\n",
    "    optimizer='sgd',\n",
    "    metrics=['accuracy']  # 需要被检验的参数\n",
    "    )"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "训练代码:  \n",
    "History 对象会记录每一批次训练的metrics"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x_train = []\n",
    "y_train = []\n",
    "history = model.fit(x_train, y_train, epochs=5, batch_size=32)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "评估模型性能"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x_test = []\n",
    "y_test = []\n",
    "model.evaluate(x=x_test,y=y_test, batch_size=128)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "预测数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "predict_data = model.predict(x_test, batch_size=128)"
   ]
  }
 ],
 "metadata": {
  "interpreter": {
   "hash": "63fd5069d213b44bf678585dea6b12cceca9941eaf7f819626cde1f2670de90d"
  },
  "kernelspec": {
   "display_name": "Python 3.9.7 64-bit",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.7"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
